<?php

namespace app\common\service;

use api\common\service\easy_pay\AliPay;
use app\common\service\easy_pay\WechatPay;

class WeiXinService
{
    //获取微信小程序openid
    public static function getXcxOpenid($code)
    {
        $appid = env('api.xcx_appid');
        $appsecret = env('api.xcx_secret');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
        // 使用 file_get_contents 发送 HTTP 请求
        $response = file_get_contents($url);
        if ($response === false) {
            return ['code' => -1, 'errmsg' => 'Request Failed'];
        }
        $result = json_decode($response, true);
        //dump($result);die;
        if (isset($result['errcode']) && $result['errcode'] !== 0) {
            return ['code' => $result['errcode'], 'errmsg' => $result['errmsg']];
        }
        return $result;
    }

    public function getPayInfo($pay_type,$order_no,$pay_price,$open_id = ''){
        $pay_price = 1;
        $url = env('api.url');
        if($pay_type == 1){
            $weChartUrl = $url  . '/server/index/wxPayBack';
            $res = (new WechatPay())->appPay($order_no,$pay_price, $weChartUrl, '在线支付');
            $data = json_decode($res->getContent(), true);
        }elseif($pay_type == 2){
            $notifyUrl =  $url  . '/server/index/aliPayBack';
            $aliPay = new AliPay();
            $res = $aliPay->appPay($order_no, $pay_price, $notifyUrl, '在线支付');
            $data = $res->getContent();
        }else{
            $weChartUrl =$url . '/api/index/wxPayBacks';
            $data = (new WechatPay())->miniPay($order_no, $pay_price, $weChartUrl, '在线支付',$open_id);
        }
        return $data;
    }
}